﻿using System;

namespace TLang.Ast
{
    using Values;

    public class IntNumNode : Node
    {

        private readonly String _content;
        private readonly int _value;


        public IntNumNode(String content, String file, int start, int end, int line, int col) : base(file, start, end, line, col)
        {
            this._content = content;

            int sign;
            if (content.StartsWith("+"))
            {
                sign = 1;
                content = content.Substring(1);
            }
            else if (content.StartsWith("-"))
            {
                sign = -1;
                content = content.Substring(1);
            }
            else
            {
                sign = 1;
            }
            int @base;
            if (content.StartsWith("0b"))
            {
                @base = 2;
                content = content.Substring(2);
            }
            else if (content.StartsWith("0x"))
            {
                @base = 16;
                content = content.Substring(2);
            }
            else if (content.StartsWith("0o"))
            {
                @base = 8;
                content = content.Substring(2);
            }
            else
            {
                @base = 10;
            }

            this._value = Convert.ToInt32(content, @base);
            if (sign == -1)
            {
                this._value = -this._value;
            }
        }


        public static IntNumNode Parse(String content, String file, int start, int end, int line, int col)
        {
            try
            {
                return new IntNumNode(content, file, start, end, line, col);
            }
            catch (FormatException)
            {
                return null;
            }
        }


        public override Value Interp(Scope s)
        {
            return new IntValue(_value);
        }

        public override String ToString()
        {
            return _value.ToString();
        }
    }
}
